var setMediaInfo = require('../../tool/setMediaInfo.js');
var models = require('../../models');
var methods = {
    'get':function (req, render) {
        render({});
    },
    'post':function (req, render, res) {
        var isAjax = req.param('ajax');
        var body = req.body;
        var mediaModel = models['media'];
        var model = new mediaModel();
        var keys = Object.keys(body);
        keys.forEach(function (key) {
            model[key] = body[key];
        });
        var callback = function () {
            model.save(function (err, doc) {
                if (err) {
                    console.log(err);
                    return;
                }
                if (isAjax) {
                    res.json(doc);
                } else {
                    render(doc);
                }
            });
        };
        var uri = body['mediaUri'];
        var mediaType = body['mediaType'];
        var setInfo = setMediaInfo[mediaType];
        setInfo(uri, model, callback);
    }
};
module.exports = function (req, res) {
    var methodName = req.method.toLowerCase();
    var render = function (data) {
        res.render('media/add', {
            'title':'Show This',
            'data':data
        }, 0);
    };
    var methodRender = methods[methodName];
    methodRender(req, render, res);
};